<template>
  <div class="setting-content inside-comment">
    <el-scrollbar height="calc(100vh - 170px)">
      <div class="exam-info">
        <h2>考试人员</h2><p>所属考试：<span>{{examName}}</span></p>
      </div>
      <div class="top-btns">
        <div class="left-box">
          <SearchCmp v-if="searchCmpArray.length" :searchCmpArray="searchCmpArray" :searchForm="queryData" @onSubmit="handleGetFormManageList" />
        </div>
        <div class="right-box">
          <el-button class="add-button" type="primary" @click="monitorDialog = true">监考</el-button>
          <el-button class="add-button" type="primary" @click="addExaminee">添加考生</el-button>
          <el-button class="add-button" type="primary" @click="importExaminee">导入考生</el-button>
        </div>
      </div>
      <RuifoxTable
        :loading="tableLoading"
        :table-data="tableData"
        :field-list="fieldList"
        :default-index="true"
        :default-checkbox="true"
      >
        <template #default-checkbox="{ element }">
          <div class="table-div-check">
            <el-checkbox
              class="unmover"
              v-model="element.checked"
              @change="handleCheckTable(element.id)"
              size=""
            />
          </div>
        </template>

        <!-- 状态 -->
        <template #status="{ element }">
          <div>
            <el-tag v-if="element.status == 'IDLE'" type="primary">未考</el-tag>
            <el-tag v-if="element.status == 'TESTING'" type="success">考试中</el-tag>
            <el-tag v-if="element.status == 'EXTENDING'" type="info">续考中</el-tag>
            <el-tag v-if="element.status == 'SUBMITTED'" type="info">已交卷</el-tag>
            <el-tag v-if="element.status == 'SCORED'" type="info">已阅卷</el-tag>
            <el-tag v-if="element.status == 'CANCELED'" type="info">取消考试</el-tag>
          </div>
        </template>

        <!-- 开始时间列 -->
        <template #startTime="{ element }">
          <span v-if="element.startTime && element.startTime != ''">{{ formatDate(element.startTime,"yyyy-MM-dd hh:mm") }}</span>
          <span v-else>-</span>
        </template>

        <!-- 提交时间列 -->
        <template #submitTime="{ element }">
          <span v-if="element.submitTime && element.submitTime != ''">{{ formatDate(element.submitTime,"yyyy-MM-dd hh:mm") }}</span>
          <span v-else>-</span>
        </template>

        <!-- 是否有效 -->
        <template #isValid="{ element }">
          <el-tag v-if="!element.isValid" type="info">-</el-tag>
          <el-tag v-else-if="element.isValid == true" type="success">是</el-tag>
          <el-tag v-else type="danger">否</el-tag>
        </template>

        <!-- 操作列 -->
        <template #options="{ element }">
          <div class="table-td-option unmover">
            <!-- <el-button type="primary" link @click="editExam(element)">阅卷</el-button> -->
            <el-button type="primary" link @click="addExamCount(element)">重考</el-button>
            <el-button type="primary" link @click="delayUser(element)" :disabled="!(element.status == 'TESTING')">延时</el-button>
            <!-- 正在考试中的用户可以踢出考试  -->
            <el-button type="danger" link @click="kickOutUser(element)" :disabled="!(element.status == 'TESTING')">踢出用户</el-button>
          </div>
        </template>
      </RuifoxTable>
      <PaginationView
        :isAffix = "false"
        :total="queryData.total"
        :pageSize="queryData.pageSize"
        :currentPage="queryData.currentPage"
        :allChoose="isAllChooseBtn"
        :pageChoose="isPageChooseBtn"
        :options="batchOptions"
        :checkedNum="checkedNum"
        :canChoose="queryData.total > 0"
        @changeSize="handleSizeChange"
        @currentChange="handleCurrentChange"
        @changePageChoose="handlePageChoose"
        @changeAllChoose="handleAllChoose"
        @invertChoose="handleInvertChoose"
        @checkOption="handleBatchOptions"
        @refreshList="handleGetFormManageList"
        @cancelChoose="handleResetPagination"
        v-if="tableData.length > 0"
      />
      <FilesUpload v-if="showFilesUpload" v-model:showDialog="showFilesUpload" :isPublic="true" @getFileList="insertFiles" :isToJpg="true" allow=".xlsx"></FilesUpload>
    </el-scrollbar>
    <!-- 选择考试用户  -->
    <el-dialog v-model="checkStudentDialog" title="选择考生" width="1100px">
      <CheckStudent ref="returnStudentRef"/>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCourseInstance = false">取消</el-button>
          <el-button type="primary" @click="submitCheckStudent">确认</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 考生考试时长延时  -->
    <el-dialog v-model="setStudentTime" title="考生考试结束时间" width="400px">
      <el-form label-width="90px">
        <el-form-item label="考生名称">
          <el-input v-model="theStudent" disabled />
        </el-form-item>
        <el-form-item label="考试结束时间">
          <el-date-picker
            v-model="formData.extendEndTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择该考生考试结束时间"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="setStudentTime = false">取消</el-button>
          <el-button type="primary" @click="submitExtendExamTime">确认</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="monitorDialog" title="考生考试结束时间" width="1200px">
      <Invigilation :examId="examId"/>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="monitorDialog = false">关闭</el-button>
          <!-- <el-button type="primary" @click="submitExtendExamTime">确认</el-button> -->
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from "vue";
import { tableList as mixTable } from '@ruifox-cms/utils'
import { 
  selectExamUserPageUser,
  batchRegisterExamUserUser,
  // registerExamUserFormExcelUser,
  extendExamTimeUser,
  increaseTryCountUser,
  kickUserUser
} from "@/api/examinee";
import { getDepartTree } from "@/api/depart";
import { formatDate } from '@/utils/tools'
import { FilesUpload } from "@ruifox-cms/components"
import { useRoute } from "vue-router";
import CheckStudent from '../components/CheckStudent.vue'
import Invigilation from '../components/Invigilation.vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const route = useRoute()
const examId = ref(route.query.id)
const examName = ref(route.query.name)

//监控弹窗显示
const monitorDialog = ref(false)
//获取部门树
const departTree = ref([]);
const transformData = (data) => {
  return data.map(item => {
    const transformedItem = {
      value: item.id,
      label: item.name
    };
    if (item.children && item.children.length > 0) {
      transformedItem.children = transformData(item.children);
    }
    return transformedItem;
  });
};
const getDepartData = async () => {
  const res = await getDepartTree({departId: "root"});
  if (res.code === 20000) {
    departTree.value = transformData(res.data.children)
    searchCmpArray.value[3].options = departTree.value
    console.log("departTree.value",departTree.value);

  }
};
const statusOption = ref([
  { label: "未考试", value: 'IDLE' },
  { label: "考试中", value: 'TESTING' },
  { label: "续考中", value: 'EXTENDING' },
  { label: "已交卷", value: 'SUBMITTED' },
  { label: "已阅卷", value: 'SCORED' },
  { label: "取消考试", value: 'CANCELED' },
]);
// const orderOption = ref([
//   { label: "正序", value: 'DESC' },
//   { label: "逆序", value: 'ASC' },
// ]);
const searchCmpArray = ref([
  { label: '用户名称', key: 'realName'},
  { label: '身份证号', key: 'identificationNumber'},
  { label: '考试状态', key: 'status', form_type: 'select', options: statusOption.value },
  { label: '所属部门', key: 'departId', form_type: 'cascader', options: departTree.value },
])

const {
  queryData,
  tableData,
  tableLoading,
  checkedNum,
  isAllChooseBtn,
  isPageChooseBtn,
  // checkedList,
  // getTableData,
  // handleSearch,
  handleCurrentChange,
  handleSizeChange,
  handlePageChoose,
  handleAllChoose,
  handleInvertChoose,
  handleCheckTable,
  handleResetPagination,
} = mixTable({
  getListApi: selectExamUserPageUser,
});
const defaultQuery = reactive({
  currentPage: 1,
  pageSize: 10,
  sort: "",
  order: "",
  checked: true,
  needToSort: true,
  sortArray: [],
  orderArray: [],
  examIds: [examId.value],
  userIds: [],
  realName: "",
  status: "",
  orderByStatement: "",
  statement: ""
});

Object.assign(queryData, defaultQuery);
watch(() => queryData, (newVal) => {
  console.log("newValue",newVal);
  
  if (Array.isArray(newVal.departId)) {
    queryData.departId = newVal.departId[newVal.departId.length - 1].toString()
  }
}, { deep: true });
// 附件上传 用户导入Excel文档
const showFilesUpload = ref(false)
const resourceFormList = ref([])
const insertFiles = filesList => {
  resourceFormList.value = filesList.map(item => {
    return {
      resourceData: {
        title: item.name,
        url: item.url,
      },
      needUpload: item.needUpload,
      tagList: item.tagList || [],
    }
  })
  //使用表格地址导入数据
  // registerExamUserFormExcelUser({fileUrl:})
  console.log("resourceFormList.value",resourceFormList.value);
}
const importExaminee = async () => {
  showFilesUpload.value = true
  console.log("点击上传Excel");
  console.log("showFilesUpload.value",showFilesUpload.value);
  
};
const handleGetFormManageList = async () => {
  try {
    let res = await selectExamUserPageUser(queryData);
    if (res.code == 20000) {
      let newList = res.data.list.map(item => {
        const { user, ...rest } = item;
        delete user.id;
        return {
          ...rest,
          ...user,
        };
      });
      tableData.value = newList;
      console.log("tableData.value",tableData.value);
    }
  } catch (error) {
    ElMessage.error("获取数据失败");
  }
};
// const handleRemoveImg = () => {
//   certificationForm.value.images[0] =  [""]
// };

//显示人员
const checkStudentDialog = ref(false);
const addExaminee = async () => {
  checkStudentDialog.value = true;
};

// 获取从子组件选择的学生列表
const returnStudentRef = ref(null)
const students = ref([])

const submitCheckStudent = async () => {
  if (returnStudentRef.value) {
    // 调用子组件暴露的方法
    students.value = returnStudentRef.value.returnStudent()
    students.value = students.value.join(",")
    const res = await batchRegisterExamUserUser({examId: examId.value, userIds:students.value})
    if(res.code == 20000){
      ElMessage.success("添加成功")
      handleGetFormManageList();
      checkStudentDialog.value = false
    }
  }
}
//用户增加考试次数
const addExamCount = async (item) => {
  const res = await increaseTryCountUser({examUserId: item.id})
  if(res.code == 20000){
    ElMessage.success("操作成功")
    handleGetFormManageList();
  }
}

//用户增加考试时长
const setStudentTime = ref(false)
const theStudent = ref()
const defaultForm = reactive({
  examUserId: "",
  extendEndTime: ""
})

//踢出用户
const kickOutUser = async (item) => {
  console.log("item",item);
  
  ElMessageBox.confirm('是否确认踢出该用户', '提示', {
    distinguishCancelAndClose: true,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const res = await kickUserUser({examUserId: item.id})
    if(res.code == 20000){
      ElMessage.success("操作成功")
      handleGetFormManageList();
    }
  }).catch(() => {
  })
 
}

const formData = ref({ ...defaultForm })
const delayUser = (row) => {
  theStudent.value = row.realName
  formData.value.examUserId = row.id
  setStudentTime.value = true
}
const submitExtendExamTime = async () => {
  if (formData.value.extendEndTime) {
    formData.value.extendEndTime = formatDate(formData.value.extendEndTime, "yyyy-MM-dd hh:mm:ss")
  }
  const res = await extendExamTimeUser(formData.value)
  if (res.code === 20000) {
    ElMessage.success("修改成功")
  }
}

const fieldList = ref([
  {
    title: "考生名称",
    name: "realName",
  },
  {
    title: "状态",
    name: "status",
  },
  {
    title: "部门",
    name: "departName",
  },
  {
    title: "开始时间",
    name: "startTime",
  },
  {
    title: "预期结束时间",
    name: "expectedEndTime",
  },
  {
    title: "提交时间",
    name: "submitTime",
  },
  {
    title: "是否有效",
    name: "isValid",
  },
  {
    title: "异常原因",
    name: "invalidReason",
  },
  {
    title: "操作",
    name: "options",
    width: 200,
    fixed: "right",
  },
]);

onMounted(async() => {
  await getDepartData();
  handleGetFormManageList();
});
</script>
<style scoped lang="scss">
.exam-info{
  display: flex;
  align-items: center;
  p{
    font-size: 16px;
    color: #555;
    margin-left: 42px;
    span{
      color: #222;
    }
  }
}
.top-btns{
  display: flex;
  margin: 10px 0;
  justify-content: space-between;
  /* align-items: center; */
  .left-box, .right-box{
    display: flex;
  }
  .add-button{
    /* margin-right: 10px; */
  }
}
</style>